import axios from "axios";
import store from "../store";

const instance = axios.create({
  baseURL: "http://39.100.95.147:1404",
  timeout: 5000,
  // headers: { "X-Host": "mall.film-ticket.film.list" },
});
// 添加请求拦截
instance.interceptors.request.use(
  function (config) {
    config.headers.token = store.state.currentUser.token;
    // console.log(config.headers.token);
    // console.log(store.state.currentUser.token);
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 添加响应拦截
instance.interceptors.response.use(
  function (response) {
    if (response.status == 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }

    // return response;
  },
  function (error) {
    let { response } = error;
    if (response) {
      switch (response.status) {
        case 404:
          throw new Error("资源返回失败");
        case 500:
          throw new Error("服务端错误");
        default:
          throw new Error("未知错误");
      }
    } else {
      throw new Error("未响应，检查网络");
    }
    return Promise.reject(error);
  }
);
export default instance;
